package cn.waka.sys.admin.filter;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import cn.waka.sys.admin.service.NodeService;
import cn.waka.sys.admin.service.RoleService;

@Component
public class UserSecurityInterceptor implements HandlerInterceptor, InitializingBean {
    private static Logger log = LoggerFactory.getLogger(UserSecurityInterceptor.class);
    @Value("${server.context.path}")
    private String contextPath;
    private NodeService nodeService;
    private RoleService roleService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {


        String uri = request.getRequestURI();
        log.debug("===访问URL：" + uri);
        if (uri.endsWith("/main") || uri.endsWith("/check") || uri.endsWith("/error") || uri.startsWith("/noauth") || uri.startsWith("/static") || uri.startsWith("/login") || uri.startsWith("/logout")) {
            return true;
        }
        if (!isNeedAuth(uri)) {

            return true;
        }


        HttpSession sess = request.getSession();
        Object uid = sess.getAttribute("uid");
        if (uid == null) {

            String xr = request.getHeader("X-Requested-With");
            //request.get
            if ("XMLHttpRequest".equals(xr)) {
                response.setContentType("application/json;charset=UTF-8");
                String rs = "{\"code\":0,\"msg\":\"会话过期，请重新登录！\",\"wait\":5,\"url\":\"" + contextPath + "login\"}";
                response.getWriter().write(rs);
            } else {
                response.sendRedirect(contextPath + "login");
            }


            return false;
        }

        String rolesStr = (String) sess.getAttribute("roles");
        if (rolesStr == null) {
            response.sendRedirect(contextPath + "login");
            return false;
        }

		
		/*List<Node> nodes=nodeService.findAll();
		if(nodes!=null&&nodes.size()>0&&!nodes.contains(uri)){
			return true;
		}*/
        boolean auth = this.isAuth(uri, rolesStr);
        if (!auth) {
            log.info("===用户[" + uid + "] 访问URL：" + uri + " 没有授权");
            String xr = request.getHeader("X-Requested-With");
            if ("XMLHttpRequest".equals(xr)) {
                response.setContentType("application/json;charset=UTF-8");
                String rs = "{\"code\":0,\"msg\":\"对不起，您没有权限使用该功能！\",\"wait\":2}";
                response.getWriter().write(rs);
            } else {
                response.sendRedirect(contextPath + "login");
            }
        }
        return auth;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
		/*HxSession session=HxSession.get();
		if(session==null){
			return;
		}
		String token=session.getToken();
		
		if(token==null){
			return;
		}
		Cookie c=new Cookie("token",token);
		response.addCookie(c);
		
		int uid=session.getUserId();
		if(uid==-1){
			redisService.del("p:token:"+token);
		}else{
			log.debug("===write session:" + token + " userId:" + uid);
			redisService.set("p:token:"+token, uid+"");
		}*/
		/*String key = "p:token:" + session.getToken();
		redisService.set(key, session.getUserId() + "");
		redisService.expire(key, 2592000);*/
    }

    @Autowired
    public void setRoleService(RoleService roleService) {
        this.roleService = roleService;
    }

    @Autowired
    public void setNodeService(NodeService nodeService) {
        this.nodeService = nodeService;
    }

    private boolean isNeedAuth(String uri) {
        List<String> nlist = nodeService.findAllURI();
        return nlist.contains(uri);
    }

    private boolean isAuth(String uri, String rolesStr) {
        if (rolesStr == null) {
            return false;
        }
		/*if(uri.startsWith("/")){
			uri=uri.substring(1);
		}*/
        String[] roleIds = rolesStr.split(",");
        for (String roleId : roleIds) {
            List<String> list = roleService.findNodeByRoleId(Integer.parseInt(roleId));
            if (list.contains(uri)) {
                log.debug("===角色授权可以访问：" + uri);
                return true;
            }
        }
        return false;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        if(contextPath==null||contextPath.length()==0){
            contextPath= "/";
        }
        if (!contextPath.endsWith("/")) {
            contextPath += "/";
        }

    }


}
